package com.lyn.solitude.pluginhost.factory

import com.lyn.solitude.pluginhost.binder.PluginHostBinder
import com.lyn.solitude.pluginhost.database.SqliteManager
import com.lyn.solitude.pluginhost.uitls.SoUtil
import dalvik.system.DexClassLoader
import java.util.UUID
import java.util.concurrent.ConcurrentSkipListMap

/**
 * 类加载器工厂
 * @author longyn 2024/05/23
 * @version 1.0.0
 */
object ClassLoaderFactory {


    @JvmStatic
    private val map: MutableMap<String, ClassLoader> = ConcurrentSkipListMap()

    @JvmStatic
    private val soPathMap: MutableMap<String, String> = ConcurrentSkipListMap()


    @JvmStatic
    fun get(path: String): ClassLoader? {
        try {
            if (map.containsKey(path)) {
                return map[path]
            }
            val extractPluginSoPath: String
            val plugin = SqliteManager.findByFilePathFirst(path)
            extractPluginSoPath = plugin?.soFolderPath
                ?: SoUtil.extractPluginSo(
                    path,
                    PluginHostBinder.pluginSoFolder.getAbsolutePath(),
                    UUID.randomUUID().toString().replace("-","")
                )

            val classLoader = DexClassLoader(
                path,
                null,
                extractPluginSoPath,
                PluginHostBinder.application.classLoader
            )
            soPathMap[path] = extractPluginSoPath
            map[path] = classLoader
            return classLoader
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return null
    }

    @JvmStatic
    fun getSoPath(path: String): String {
        soPathMap[path]?.let {
            return it
        }
        return ""
    }


    @JvmStatic
    fun remove(path: String) {
        try {
            map.remove(path)
            val soFolderPath = soPathMap[path]
            soFolderPath?.let {
                PluginHostBinder.pluginSoFolder.deleteFolderFile(soFolderPath)
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }
}